import { reqRegCode, reqRegister, reqLogin, reqGetUserInfo, reqLogout } from "@/api"
import { setToken, getToken } from "@/utils/token"

const user = {
    state: {
        code: '',
        token: getToken(),
        userInfo: {}
    },
    mutations: {
        GETCODE(state, code) {
            state.code = code
        },
        LOGIN(state, token) {
            state.token = token
        },
        GETUSERINFO(state, userInfo) {
            state.userInfo = userInfo
        },
        LOGOUT(state) {
            state.token = ''
            state.userInfo = {}
        }
    },
    actions: {
        async getCode({ commit }, phone) {
            let res = await reqRegCode(phone)
            if (res.code === 200) {
                commit('GETCODE', res.data)
                return 'ok'
            } else {
                throw new Error('返回验证码失败')
            }
        },
        async doRegister({ commit }, params) {
            let res = await reqRegister(params)
            if (res.code === 200) {
                return 'ok'
            } else {
                throw new Error('注册失败')
            }
        },
        async login({ commit }, params) {
            let res = await reqLogin(params)
            if (res.code === 200) {
                commit('LOGIN', res.data.token)
                setToken(res.data.token)
                return 'ok'
            } else {
                throw new Error('登陆失败')
            }
        },
        async getUserInfo({ commit, state }) {
            if (!state.userInfo.name) {
                // 如果没有用户信息
                let res = await reqGetUserInfo()
                if (res.code === 200) {
                    commit('GETUSERINFO', res.data)
                    return 'ok'

                } else {
                    throw new Error('获取用户信息失败')
                }
            }
            return 'ok'

        },
        async logout({ commit }) {
            let res = await reqLogout()
            if (res.code === 200) {
                commit('LOGOUT')
                setToken('')
                return 'ok'
            } else {
                throw new Error('退出登录失败了')
            }
        }
    },
    getters: {
    }
}
export default user